<!--
 * @Date: 2022-01-05 09:25:24
 * @LastEditors: 春贰
 * @Desc: 
 * @LastEditTime: 2022-03-16 18:35:35
 * @FilePath: \web\src\view\system\role\modal\edit.vue
-->
<template>
  <a-modal
    :visible="visible"
    :title="t('edit')"
    :cancelText="t('cancel')"
    :okText="t('submit')"
    @ok="submit"
    @cancel="cancel(false)"
  >
    <a-form
      ref="formRef"
      :model="record"
      :rules="formRules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
    >
      <a-form-item ref="name" :label="t('name')" name="name">
        <a-input v-model:value="record.name" />
      </a-form-item>
      <a-form-item ref="desc" :label="t('desc')" name="desc">
        <a-input v-model:value="record.desc" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script>
import { useI18n } from "vue-i18n";
import { message } from "ant-design-vue";
import { edit } from "@/core/api/module/role";
import { defineComponent, reactive, ref, toRaw, watch } from "vue";
export default defineComponent({
  props: {
    visible: {
      type: Boolean,
    },
    record: {
      type: Object,
    },
  },
  emit: ["close"],
  setup(props, context) {
    const { t } = useI18n();
    const state = reactive({ 
    });

    const formRef = ref();

    let formState = reactive({});

    const formRules = {
      name: [{ required: true , message: t('Please input user name'), trigger: "blur" }],
    };

    const submit = (e) => { 
      formRef.value
        .validate()
        .then(() => {
          edit(toRaw(props.record)).then((response) => {
            if (response.code == 0) {
              message.success({ content: t('Saved successfully!'), duration: 1 }).then(() => {
                cancel(true);
              });
            } else {
              message.error({ content: response.msg, duration: 1 }).then(() => {
                cancel(false);
              });
            }
          });
        })
        .catch((error) => {
          console.log("error", error);
        });
    };

    const cancel = (e = false) => {
      formRef.value.resetFields();
      context.emit("close", e);
    };

    return {
      t,
      state,
      submit,
      cancel,
      formRef,
      formState,
      formRules,

      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
    };
  },
});
</script>